#include "StdAfx.h"
#include "WinBoardReceiver.h"

#include <string>

#include "WinBoardMessage.h"

using namespace Rorn::Chess;

WinBoardReceiver::WinBoardReceiver(IAppSender* appSender, IEngine* theEngine) 
	: inputQueue_(),
	  inputThread_(inputQueue_),
	  appSender_(appSender),
	  theEngine_(theEngine)
{
	isTimeToQuit_ = false;
}

/*virtual*/ WinBoardReceiver::~WinBoardReceiver(void)
{
}

/*virtual*/ bool WinBoardReceiver::IsTimeToQuit()
{
	return isTimeToQuit_;
}

/*virtual*/ void WinBoardReceiver::Update()
{
	while(inputQueue_.HasMessages())
	{
		std::string message;
		inputQueue_.GetNextMessage(message);

		ProcessMessage(message);
	}
}

void WinBoardReceiver::ProcessMessage(const std::string& messageText)
{
	WinBoardMessage message(messageText);

	if(message.GetCommand() == "force")
	{
		ProcessForceMessage(message);
	}
	else if(message.GetCommand() == "go")
	{
		ProcessGoMessage(message);
	}
	else if(message.GetCommand() == "level")
	{
		ProcessLevelMessage(message);
	}
	else if(message.GetCommand() == "new")
	{
		ProcessNewMessage(message);
	}
	else if(message.GetCommand() == "post")
	{
		ProcessPostMessage(message);
	}
	else if(message.GetCommand() == "protover")
	{
		ProcessProtoVerMessage(message);
	}
	else if(message.GetCommand() == "quit")
	{
		ProcessQuitMessage(message);
	}
	else if(message.GetCommand() == "random")
	{
		ProcessRandomMessage(message);
	}
	else if(message.GetCommand() == "usermove")
	{
		ProcessUserMoveMessage(message);
	}
	else if(message.GetCommand() == "xboard")
	{
		ProcessXBoardMessage(message);
	}
	else
	{
		// Log something
	}
}

void WinBoardReceiver::ProcessForceMessage(const WinBoardMessage& message)
{
	// Nothing to do, the engine assumes evaluate only mode
}

void WinBoardReceiver::ProcessGoMessage(const WinBoardMessage& message)
{
	// TODO - get the engine to play as the currnet player
}

void WinBoardReceiver::ProcessLevelMessage(const WinBoardMessage& message)
{
}

void WinBoardReceiver::ProcessNewMessage(const WinBoardMessage& message)
{
	theEngine_->StartNewGame();
}

void WinBoardReceiver::ProcessPostMessage(const WinBoardMessage& message)
{
}

void WinBoardReceiver::ProcessProtoVerMessage(const WinBoardMessage& message)
{
	appSender_->Post("feature usermove=1 done=1");
}

void WinBoardReceiver::ProcessQuitMessage(const WinBoardMessage& message)
{
	isTimeToQuit_ = true;
}

void WinBoardReceiver::ProcessRandomMessage(const WinBoardMessage& message)
{
}

void WinBoardReceiver::ProcessUserMoveMessage(const WinBoardMessage& message)
{
}

void WinBoardReceiver::ProcessXBoardMessage(const WinBoardMessage& message)
{
	appSender_->Post("");// Ack
}